<template>
  <div class="box">
    <el-form
      ref="loginForm"
      :model="from"
      :rules="rules"
      label-width="80px"
      class="login-box"
    >
      <h3 class="login-title">管理员登录</h3>
      <el-form-item label="账号" prop="username">
        <el-input
          type="text"
          placeholder="请输入账号"
          v-model="from.username"
        />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input
          type="password"
          placeholder="请输入密码"
          v-model="from.password"
        />
      </el-form-item>
      <el-form-item class="fotm-loginBtn">
        <el-button type="primary" @click="onSubmit('loginForm')"
          >登 录</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: "controllerLogin",
  data() {
    return {
      from: {
        username: "",
        password: "",
      },
      //表单验证，需要在 el-form-item 元素中增加 prop 属性
      rules: {
        username: [
          { required: true, message: "账号不能为空", trigger: "blur" },
        ],
        password: [
          { required: true, message: "密码不能为空", trigger: "blur" },
        ],
      }, //对话框的显示和隐藏
      dialogVisible: false,
    };
  },
  created() {
    if (sessionStorage.getItem("controllerInfo")) {
      this.$router.push("/controller");
    }
    document.onkeydown = (e) => {
      let key = window.event.keyCode;
      if (key == 13) {
        this.onSubmit("loginForm");
      }
    };
  },
  methods: {
    onSubmit(formName) {
      //为表单绑定验证功能
      this.$refs[formName].validate((valid) => {
        if (valid) {
          //使用vue-router路由到指定页面
          if (this.from.username != "admin") {
            this.$message.error("账号不正确");
            return;
          }
          if (this.from.password != 123456) {
            this.$message.error("密码不正确");
            return false;
          }
          this.$router.push("/controller");
          this.$message({
            message: "登录成功",
            type: "success",
          });
          sessionStorage.setItem("controllerInfo", JSON.stringify(this.from));
        } else {
          // this.$message.error('登录失败');
          return false;
        }
      });
    },
    handleClose() {},
  },
};
</script>

<style scoped>
.box {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}
.login-box {
  border: 1px solid #dcdfe6;
  width: 350px;
  margin: 180px auto;
  padding: 35px 35px 15px 35px;
  border-radius: 5px;
  box-shadow: 0 0 25px #909399;
}
.login-title {
  text-align: center;
  margin: 0 auto 40px auto;
  color: #303133;
}

.el-button {
  width: 60%;
}
</style>